package service

import (
	"errors"
	"time"
)
import "../model"

type ContactService struct {
}

/**
 * 添加好友
 */
func (contactService *ContactService) AddFriend(ownerId, dstId int64) error {

	if ownerId == dstId {
		return errors.New("不能添加自己.")
	}

	contact := model.Contact{}
	_, err := DBEngine.Where("owner_id = ?", ownerId).
		And("dst_id = ?", dstId).
		And("type = ?", model.TYPE_USER).
		Get(&contact)
	if err != nil {
		return err
	}

	if contact.Id > 0 {
		return errors.New("你们已经是好友了")
	}

	session := DBEngine.NewSession()
	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.InsertOne(model.Contact{
		OwnerId:  ownerId,
		DstId:    dstId,
		Type:     model.TYPE_USER,
		CreateAt: time.Now(),
	})
	if err != nil {
		err2 := session.Rollback()
		if err2 != nil {
			return err2
		}
		return err
	}

	_, err = session.InsertOne(model.Contact{
		OwnerId:  dstId,
		DstId:    ownerId,
		Type:     model.TYPE_USER,
		CreateAt: time.Now(),
	})
	if err != nil {
		err2 := session.Rollback()
		if err2 != nil {
			return err2
		}
		return err
	}

	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

/**
 * 获得好友列表
 */
func (contactService *ContactService) GetFriendList(ownerId int64) (friendList []model.MobileUser, err error) {

	contactList := make([]int64, 0)
	err = DBEngine.Table("contact").Cols("dst_id").Where("owner_id = ?", ownerId).Find(&contactList)
	if err != nil {
		return nil, err
	}

	err = DBEngine.In("id", contactList).Find(&friendList)
	if err != nil {
		return nil, err
	}

	return friendList, err
}
